package com.shfl.servermanage.shell;

import ch.ethz.ssh2.*;
import com.shfl.servermanage.exception.ApiException;
import com.shfl.servermanage.shell.info.RemoteConnectInfo;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.ConnectException;

public class RemoteConnectUtil {


    private RemoteConnectUtil() {
    }

    /**
     * 上传文件到服务器
     *
     * @param f                     文件对象
     * @param length                文件大小
     * @param remoteTargetDirectory 上传路径
     * @param mode                  默认为null
     */
    public static void uploadFile(RemoteConnectInfo info, File f, long length, String remoteTargetDirectory, String mode) {
        Connection connection = new Connection(info.getIp(), info.getPort());
        SCPOutputStream os = null;
        FileInputStream fis = null;
        try {
            connection.connect();
            boolean isAuthenticated = connection.authenticateWithPassword(info.getName(), info.getPassword());
            if (!isAuthenticated) {
                return;
            }
            SCPClient scpClient = new SCPClient(connection);
            os = scpClient.put(f.getName(), length, remoteTargetDirectory, mode);
            byte[] b = new byte[4096];
            fis = new FileInputStream(f);
            int i;
            while ((i = fis.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }

    public static void sendShell(RemoteConnectInfo info, String shell, StringBuilder sb) throws Exception {
        Connection connection = new Connection(info.getIp(), info.getPort());
        Session ssh = null;
        try {
            connection.connect();
            boolean isAuthenticated = connection.authenticateWithPassword(info.getName(), info.getPassword());
            if (!isAuthenticated) {
                throw new ApiException("1300");
            }
            if (StringUtils.isEmpty(shell)) {
                return;
            }
            ssh = connection.openSession();
            ssh.execCommand(shell);
            //将Terminal屏幕上的文字全部打印出来
            InputStream is = new StreamGobbler(ssh.getStdout());
            BufferedReader brs = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String line = brs.readLine();
                if (line == null) {
                    break;
                }
                sb.append("\r\n");
                sb.append(line);
                System.out.println(line);
            }
            System.out.println(sb.toString());
        }catch (ConnectException e){
            throw new ApiException("1301");
        }
        finally {
            //连接的Session和Connection对象都需要关闭
            if (ssh != null) {
                ssh.close();
            }
            connection.close();
        }

    }


    public static void main(String[] args) {
        RemoteConnectInfo info = new RemoteConnectInfo();
        info.setIp("121.40.115.235");
        info.setPort(22);
        info.setName("root");
        info.setPassword("5KeepMoving@");
        File f = new File("D:\\caoxin\\5KM\\binlog 日志处理.txt");
        uploadFile(info, f, f.length(), "/www/wwwroot/fkm", null);
    }

}
